package com.orm.mybatisplus.config;

import com.orm.mybatisplus.util.DbUtil;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 动态数据源
 *
 */
public class DynamicDataSource extends AbstractRoutingDataSource {
    private static DynamicDataSource instance;
    private static byte[] lock=new byte[0];
    private static Map<Object,Object> dataSourceMap=new HashMap<Object, Object>();
//    private AtomicInteger count = new AtomicInteger(0);  //读写分离

    @Override
    public void setTargetDataSources(Map<Object, Object> targetDataSources) {
        super.setTargetDataSources(targetDataSources);
        dataSourceMap.putAll(targetDataSources);
        // 必须添加该句，否则新添加数据源无法识别到
        super.afterPropertiesSet();
    }

    public Map<Object, Object> getDataSourceMap() {
        return dataSourceMap;
    }

    /**
     * 核心方法，切换数据源上下文
     */
    @Override
    protected Object determineCurrentLookupKey() {
        String dbKey = DatabaseContextHolder.getDBKey();
        System.out.println(Thread.currentThread().getName()+" dbKey:    "+dbKey);
        return dbKey;
    }

    /**
     * 核心方法，切换数据源上下文 读写分离
     */
//    @Override
//    protected Object determineCurrentLookupKey() {
//        String dbKey = DatabaseContextHolder.getDBKey();
//        if (dbKey.equals(DbUtil.DB_MASTER1)) // 如果是写库，直接返回
//            return dbKey;
//        // 读 简单负载均衡
//        int number = Math.abs(count.getAndAdd(1));
//        int lookupKey = number % 2;
//        if (lookupKey==1){
//        return DbUtil.DB_MASTER2;
//        }else{
//        return DbUtil.DB_MASTER3;
//        }
//    }


    @Override
    protected DataSource determineTargetDataSource() {
        return super.determineTargetDataSource();
    }

    private DynamicDataSource() {}

    public static synchronized DynamicDataSource getInstance(){
        if(instance==null){
            synchronized (lock){
                if(instance==null){
                    instance=new DynamicDataSource();
                }
            }
        }
        return instance;
    }

}
